<?php


namespace App\Service\Store;

use App\Constants\Business;
use App\Dao\UserDao;
use Hyperf\Di\Annotation\Inject;

/**
 * 商家服务（非审核）
 * Class SellerService
 * @package App\Service\Store
 */
class SellerService
{
    /**
     * 商家服务（审核）
     * @Inject()
     * @var BusinessService
     */
    public $business_service;

    /**
     * @Inject()
     * @var UserDao
     */
    public $user_dao;

    /**
     * 获取商家列表根据条件参数
     * @param array $params
     * @return array|mixed
     */
    public function getBusinessList(array $params)
    {
        $map = [];

        isset($params['start_time']) && !isset($params['end_time']) && !empty($params['start_time']) && $map['created_at'] = ['>=', strtotime($params['start_time'])]; // 创建认证开始时间
        isset($params['end_time']) &&  !isset($params['start_time'])&& !empty($params['end_time'])  && $map['created_at'] = ['<=', strtotime($params['end_time'])]; // 创建认证结束时间

        isset($params['end_time']) &&  isset($params['start_time'])
        && !empty($params['end_time']) && !empty($params['start_time'])
        && $map['between_field'] = ['created_at' =>[strtotime($params['start_time']), strtotime($params['end_time'])]]; // 有创建开始和结束时间

        isset($params['status']) && $map['status'] = (int)$params['status']; // 商户状态/0=禁用/1=正常/2=待审核/3=审核未通过
        isset($params['phone'])  && !empty($params['phone']) && $map['phone'] = ['like', "%{$params['phone']}%"]; // 手机号
        if ( isset($params['account'])  && !empty($params['account']) ) { // 账号
            $user_map['phone'] = ['like', "%{$params['account']}%"]; // 匹配user表的phone字段
            $users = $this->user_dao->getUsersByMap($user_map, null, ['id'])->toArray();
            $user_ids = array_column($users, 'id');
            $map['user_id'] = ['in', $user_ids];
        }

        isset($params['legal_name'])  && !empty($params['legal_name']) && $map['legal_name'] = ['like', "%{$params['legal_name']}%"]; // 法人代表姓名/姓名
        isset($params['address'])  && !empty($params['address']) && $map['address'] = ['like', "%{$params['address']}%"]; // 商家详细地址
        // 入驻方式
        if (isset($params['entry_way'])) {
            switch ($params['entry_way']){
                case Business::ENABLE_FULL_DISCOUNT:
                    $map['enable_full_discount'] = 1; // 全店入驻
                    break;
                case Business::ENABLE_COUPON:
                    $map['enable_coupon'] = 1; // 优惠券
                    break;
                case Business::ENABLE_VOUCHER:
                    $map['enable_voucher'] = 1; // 现金抵用券
                    break;
                default:
                    break;
            }
        }

        isset($params['search'])  && !empty($params['search']) && $map['name'] = ['like', "%{$params['search']}%"]; // 搜索 /  商家简称

        $sort = 'created_at desc';
        $select = ['id', 'created_at', 'user_id', 'name', 'phone', 'legal_name', 'address' ,'enable_full_discount', 'full_discount_rate', 'enable_coupon', 'enable_voucher', 'status', 'parent_id'];
        // 分页
        $page_size = null;
        isset($params['page']) && $page_size = isset($params['page_size'])? $params['page_size']: 20;
        $business_list = $this->business_service->dao->getBusinessByMap($map, $sort, $select, $page_size)->toArray();
        if (isset($business_list['data'])) {
            $business_list['data'] = $this->joinRelatedData($business_list['data'], $select);
        } else {
            $business_list = $this->joinRelatedData($business_list, $select);
        }
        return $business_list;
    }

    /**
     * 数据拼装
     * @param array $business_list
     * @param array $select
     * @return array
     */
    public function joinRelatedData(array $business_list, array $select)
    {
        $parent_users = null;

        $user_ids = array_column($business_list, 'user_id');
        $user_phones = $this->user_dao->getUsersByIdsNotGroup($user_ids, ['id', 'phone'])->pluck('phone', 'id')->toArray(); // 为了获取自己user的phone
        // 上级渠道商获取
        if (in_array('parent_id', $select)) {
            $parent_ids = array_unique(array_filter(array_column($business_list, 'parent_id')));
            $parent_users = $this->user_dao->getUserByIds($parent_ids, ['id', 'name', 'phone'])->toArray();
        }

        foreach ($business_list as $key => $item) {
            $business_list[$key]['account'] = $user_phones[$item['user_id']]??""; // 账号
            // 上级渠道商
           if ( isset($parent_users[$item['parent_id']])) {
               foreach ($parent_users[$item['parent_id']] as $parent_user) {
                   $business_list[$key]['parent_user_name'] = $parent_user['name']; // 上级渠道商姓名
                   $business_list[$key]['parent_phone'] = $parent_user['phone']; // 上级渠道商账号
               }
           } else {
               $business_list[$key]['parent_user_name'] = "无"; // 上级渠道商姓名
               $business_list[$key]['parent_phone'] = "无"; // 上级渠道商账号
           }
           // 入驻方式
           if ($item['enable_full_discount'] == 1) { // 全店入驻
                $business_list[$key]['entry_way'] = '全店入驻';
           }
           if ($item['enable_coupon'] == 1) { // 优惠券
                $business_list[$key]['entry_way'] = '优惠券';
           }
           if ($item['enable_voucher'] == 1) { // 现金抵用券
                $business_list[$key]['entry_way'] = '现金抵用券';
           }
           // 商家状态
            if (isset($item['status'])) {
                $business_list[$key]['status_text'] = Business::STATUS_LIST[(int)$item['status']]??'无';
            } else {
                $business_list[$key]['status_text'] = '无';
            }
            // 创建时间
            $business_list[$key]['create_time'] = date('Y-m-d H:i:s', (int)$item['created_at']);

        }

        return $business_list;
    }

}